﻿using System;
using System.Net;
using System.Net.Sockets;

namespace UdpAsyncEcho
{
    static class Utility
    {
        public static void StartReceive(this Socket socket, SocketAsyncEventArgs evtargs,
            IPEndPoint remoteEndpoint, byte[] buffer,
            Action<SocketAsyncEventArgs> recvCallback)
        {
            evtargs.SetBuffer(buffer, 0, buffer.Length);
            evtargs.RemoteEndPoint = remoteEndpoint;

            if (!socket.ReceiveFromAsync(evtargs))
                recvCallback(evtargs);
        }

        public static void StartSend(this Socket socket, SocketAsyncEventArgs evtargs,
            IPEndPoint remoteEndpoint, byte[] buffer,
            Action<SocketAsyncEventArgs> sentCallback)
        {
            evtargs.SetBuffer(buffer, 0, buffer.Length);
            evtargs.RemoteEndPoint = remoteEndpoint;

            if (!socket.SendToAsync(evtargs))
                sentCallback(evtargs);
        }
    }
}
